﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SimpleBoard.Binary;
using SimpleBoard.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;

namespace SimpleBoard.Runtime
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private readonly IHost host;

        public App()
        {
            var hostBuilder = Host.CreateDefaultBuilder()
                                  .UseAutoInjection()
                                  .ConfigureServices(services =>
                                  {
                                      services.AddSingleton<IPageGenerator>(LoadPageGenerator());
                                  });

            host = hostBuilder.Build();
        }

        public static new App Current => (App)Application.Current;

        private void OnStartup(object sender, StartupEventArgs e)
        {
            App.AutoWired<MainWindow>().Show();
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
        }

        private IPageGenerator LoadPageGenerator()
        {
            var controlAssemblyDirectory = new DirectoryInfo("App");
            if (!controlAssemblyDirectory.Exists) controlAssemblyDirectory.Create();

            var dll = controlAssemblyDirectory.GetFiles().Where(x => x.Name == "App.dll").Single();

            var assembly = Assembly.LoadFrom(dll.FullName);
            return Activator.CreateInstance(assembly.GetTypes().Where(x => x.IsAssignableTo(typeof(IPageGenerator))).First()) as IPageGenerator
                   ?? throw new InvalidCastException();
        }

        internal static T AutoWired<T>()
        {
            var service = Current.host.Services.GetService<T>();
            if (service is null) throw new NullReferenceException($"服务{typeof(T)}不存在");
            return service;
        }

    }
}
